package com.itheima.service.impl;

import com.itheima.mapper.EcometeorologyMapper;
import com.itheima.pojo.Ecometeorology;
import com.itheima.pojo.Flux;
import com.itheima.pojo.Meteorology;
import com.itheima.service.EcometeorologyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EcometeorologyServiceImpl implements EcometeorologyService {
    @Autowired
    private EcometeorologyMapper ecometeorologyMapper;

    @Override
    public void add(Ecometeorology ecometeorology) {
        ecometeorologyMapper.add(ecometeorology);
    }

    @Override
    public Ecometeorology findEcometeorologyByTimestamp(LocalDateTime TimeStamp) {
        Ecometeorology ecometeorology = ecometeorologyMapper.findEcometeorologyByTimestamp(TimeStamp);
        return ecometeorology;
    }

    @Override
    public List<Ecometeorology> findEcometeorologyByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        List<Ecometeorology> ecometeorologyList= ecometeorologyMapper.findEcometeorologyByTimeRange(startTime,endTime);
        return ecometeorologyList;
    }

    @Override
    public List<Ecometeorology> findEcometeorologyInLatestDayData(){
        List<Ecometeorology> ecometeorologyList = ecometeorologyMapper.findEcometeorologyInLatestDayData();
        return ecometeorologyList;
    }

    @Override
    public Ecometeorology findEcometeorologyByUserSelectSingleTimeStamp(LocalDateTime TimeStamp) {
        // 数据每半个小时一条，首先将数据转化为距离该时间戳最近的数据节点
        // 例如：2025-02-09 03:01:00 转化为 2025-02-09 03:00:00
        //      2025-02-09 03:29:00 转化为 2025-02-09 03:00:00
        //      2025-02-09 03:31:00 转化为 2025-02-09 03:30:00

        // 获取输入时间戳的分钟数
        int minute = TimeStamp.getMinute();

        // 计算最近的时间节点
        LocalDateTime newTimeStamp;
        if (minute < 15) {
            // 如果分钟数小于15，则归到当前小时的00分
            newTimeStamp = TimeStamp.withMinute(0).withSecond(0).withNano(0);
        } else if (minute < 45) {
            // 如果分钟数在15到44之间，则归到当前小时的30分
            newTimeStamp = TimeStamp.withMinute(30).withSecond(0).withNano(0);
        } else {
            // 如果分钟数大于等于45，则归到下一小时的00分
            newTimeStamp = TimeStamp.plusHours(1).withMinute(0).withSecond(0).withNano(0);
        }

        // 然后再通过该节点查询数据
        Ecometeorology ecometeorology = ecometeorologyMapper.findEcometeorologyByTimestamp(newTimeStamp);

        return ecometeorology;
    }

    @Override
    public Ecometeorology findLatestEcometeorology() {
        Ecometeorology latestEcometeorology = ecometeorologyMapper.findLatestEcometeorology();
        return latestEcometeorology;
    }
}
